package com.example.backend.common.tree;

import com.example.backend.entity.Permission;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 树形结构构建器
 */
@Component
public class TreeBuilder {
    
    /**
     * 构建菜单树
     */
    public List<MenuTree> buildTree(List<Permission> permissions) {
        // 按类型分组
        Map<Integer, List<Permission>> typeMap = permissions.stream()
                .collect(Collectors.groupingBy(Permission::getType));
        
        // 获取菜单类型的权限(type=0或1)
        List<Permission> menuPermissions = typeMap.entrySet().stream()
                .filter(e -> e.getKey() <= 1)
                .flatMap(e -> e.getValue().stream())
                .collect(Collectors.toList());
        
        // 获取按钮类型的权限(type=2)
        List<Permission> buttonPermissions = typeMap.getOrDefault(2, new ArrayList<>());
        
        // 按钮权限按父ID分组
        Map<Long, List<String>> buttonMap = buttonPermissions.stream()
                .collect(Collectors.groupingBy(Permission::getParentId,
                        Collectors.mapping(Permission::getCode, Collectors.toList())));
        
        // 转换为MenuTree对象
        List<MenuTree> menuTrees = menuPermissions.stream()
                .map(p -> convertToMenuTree(p, buttonMap))
                .collect(Collectors.toList());
        
        // 构建树形结构
        Map<Long, List<MenuTree>> parentMap = menuTrees.stream()
                .collect(Collectors.groupingBy(MenuTree::getParentId));
        
        menuTrees.forEach(menu -> menu.setChildren(parentMap.get(menu.getId())));
        
        // 返回顶级菜单
        return menuTrees.stream()
                .filter(menu -> menu.getParentId() == 0)
                .sorted((m1, m2) -> m1.getSort() - m2.getSort())
                .collect(Collectors.toList());
    }
    
    /**
     * 权限对象转换为菜单树节点
     */
    private MenuTree convertToMenuTree(Permission permission, Map<Long, List<String>> buttonMap) {
        MenuTree menu = new MenuTree();
        menu.setId(permission.getId());
        menu.setParentId(permission.getParentId());
        menu.setName(permission.getName());
        menu.setPath(permission.getPath());
        menu.setComponent(permission.getComponent());
        menu.setRedirect(permission.getRedirect());
        menu.setIcon(permission.getIcon());
        menu.setHidden(permission.getHidden() == 1);
        menu.setKeepAlive(permission.getKeepAlive() == 1);
        menu.setSort(permission.getSort());
        menu.setPermission(permission.getCode());
        // 设置按钮权限
        menu.setButtons(buttonMap.getOrDefault(permission.getId(), new ArrayList<>()));
        return menu;
    }
} 